<template>
  <a-modal
    v-model:visible="visible"
    title="修改设备流转信息"
    :mask-closable="false"
    :esc-to-close="false"
    draggable
    :width="modalWidth"
    @before-ok="handleSave"
    @close="handleReset"
  >
    <a-form
      ref="formRef"
      :model="formState"
      :layout="formLayout"
      :size="formSize"
      @submit-success="handleSave"
    >
      <!-- 新增：项目任务选择卡片 -->
      <a-card title="关联试验任务" :bordered="false" class="project-task-card" :body-style="{ padding: '16px 0' }">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="选择项目" field="projectId" :rules="requiredRule" label-col-flex="80px">
              <a-select 
                v-model="selectedProject" 
                :options="projectOptions" 
                placeholder="请选择项目" 
                allow-clear
                @change="handleProjectChange" 
                :loading="projectLoading"
              >
                <template #suffix>
                  <icon-search />
                </template>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="选择任务" field="taskId" label-col-flex="80px">
              <a-select 
                v-model="formState.taskId" 
                :options="taskOptions" 
                placeholder="请先选择项目" 
                allow-clear
                :disabled="!selectedProject" 
                :loading="taskLoading"
              >
                <template #suffix>
                  <icon-search />
                </template>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-card>

      <a-divider orientation="left">设备信息</a-divider>

      <a-row :gutter="gridGutter">
        <!-- 放置位置 -->
        <a-col :span="24">
          <a-form-item
            label="放置位置"
            field="location"
            :rules="locationRules"
          >
            <a-input
              v-model="formState.location"
              placeholder="请输入放置位置"
            />
          </a-form-item>
        </a-col>

        <!-- 状态 -->
        <a-col :span="12">
          <a-form-item
            label="状态"
            field="status"
          >
            <a-select
              v-model="formState.status"
              :options="statusOptions"
            />
          </a-form-item>
        </a-col>

        <!-- 使用时间 -->
        <a-col :span="12">
          <a-form-item
            label="使用时间"
            field="useTime"
            :rules="requiredRule"
          >
            <a-date-picker
              v-model="formState.useTime"
              show-time
              format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>

        <!-- 使用人 -->
        <a-col :span="12">
          <a-form-item
            label="使用人"
            field="userId"
            :rules="requiredRule"
          >
            <a-select
              v-model="formState.userId"
              :options="userOptions"
              :loading="userLoading"
              :field-names="{ value: 'id', label: 'nickname' }"
              @search="handleUserSearch"
            />
          </a-form-item>
        </a-col>

        <!-- 归还时间 -->
        <a-col :span="12">
          <a-form-item
            label="归还时间"
            field="backTime"
          >
            <a-date-picker
              v-model="formState.backTime"
              show-time
              format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>

        <!-- 报废时间 -->
        <a-col :span="12">
          <a-form-item
            label="报废时间"
            field="scarpTime"
          >
            <a-date-picker
              v-model="formState.scarpTime"
              show-time
              format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, computed, nextTick } from 'vue'
import { useWindowSize } from '@vueuse/core'
import { 
  type DeviceCirculationResp,
  type DeviceCirculationUpdateReq,
  updateDeviceCirculation,
  searchUsers
} from '@/apis/generator/deviceCirculation'
import type { UserOption } from '@/apis/generator/deviceCirculation'
import { Message } from '@arco-design/web-vue'
import { listProjectStats, listTaskStats } from '@/apis/task/taskSituationChart'

const emit = defineEmits(['save-success'])

// 响应式数据
const { width } = useWindowSize()
const visible = ref(false)
const formRef = ref()
const currentRecord = ref<string>() 
const userLoading = ref(false)
const userOptions = ref<UserOption[]>([])

// 项目任务选择相关
const selectedProject = ref<number | null>(null)
const projectOptions = ref<{ value: number, label: string }[]>([])
const taskOptions = ref<{ value: number, label: string }[]>([])
const projectLoading = ref(false)
const taskLoading = ref(false)

// 计算属性
const modalWidth = computed(() => width.value >= 800 ? '800px' : '100%')
const formLayout = 'vertical'
const formSize = 'large'
const gridGutter = 16

// 表单验证规则
const requiredRule = { required: true, message: '必填项' }
const locationRules = [
  requiredRule,
  { max: 255, message: '最长255字符' }
]

// 状态选项
const statusOptions = [
  { value: 0, label: '归还' },
  { value: 1, label: '在用' },
  { value: 2, label: '外借' },
  { value: 3, label: '报废' }
]

// 表单状态
const formState = ref({
  location: '',
  status: undefined as number | undefined,
  useTime: '',
  taskId: undefined as number | undefined,
  userId: undefined as number | undefined,
  backTime: undefined as string | undefined,
  scarpTime: undefined as string | undefined,
})

// 获取项目列表
const fetchProjects = async () => {
  projectLoading.value = true
  try {
    const res = await listProjectStats()
    if (res.success && res.data && res.data.data) {
      projectOptions.value = res.data.data.map((item: any) => ({
        value: item.id,
        label: `${item.name} (${item.taskCount}个任务)`
      }))
    }
  } catch (error) {
    console.error('获取项目列表失败:', error)
    Message.error('获取项目列表失败')
  } finally {
    projectLoading.value = false
  }
}

// 项目变更时获取任务列表
const handleProjectChange = async (projectId: number) => {
  formState.value.taskId = undefined
  taskOptions.value = []
  taskLoading.value = true

  try {
    const res = await listTaskStats(projectId)
    if (res.success && res.data) {
      taskOptions.value = res.data.data.map(item => ({
        value: item.id,
        label: `${item.name} (总试验次数: ${item.taskTestLogTotal}h)`
      }))
    }
  } catch (error) {
    console.error('获取任务列表失败:', error)
    Message.error('获取任务列表失败')
  } finally {
    taskLoading.value = false
  }
}

const handleUserSearch = async () => {
  try {
    userLoading.value = true
    const res = await searchUsers()
    console.log("API返回数据:", res) 
    userOptions.value = res.map(user => ({
      id: user.id,
      nickname: user.nickname || '未知用户'
    }))
  } catch (error) {
    console.error('搜索用户失败:', error)
    Message.error('搜索用户失败')
  } finally {
    userLoading.value = false
  }
}

const handleReset = async () => {
  await nextTick()
  formRef.value?.resetFields()
  formState.value = {
    location: '',
    status: undefined,
    useTime: '',
    taskId: undefined,
    userId: undefined,
    backTime: undefined,
    scarpTime: undefined,
  }
  selectedProject.value = null
  taskOptions.value = []
  userOptions.value = []
  currentRecord.value = undefined
}

const handleSave = async () => {
  try {
    await formRef.value?.validate()
    
    if (!currentRecord.value) {
      console.error('未获取到设备ID')
      Message.error('未获取到设备ID')
      return false
    }

    const submitData: DeviceCirculationUpdateReq = {
      circulationId: currentRecord.value,
      location: formState.value.location,
      status: formState.value.status,
      useTime: formState.value.useTime,
      taskId: formState.value.taskId !== undefined ? formState.value.taskId.toString() : undefined,
      userId: formState.value.userId !== undefined ? formState.value.userId.toString() : undefined,
      backTime: formState.value.backTime,
      scarpTime: formState.value.scarpTime,
    }

    const response = await updateDeviceCirculation(submitData)

    if (!response?.success) {
      console.error('更新失败:', response?.msg)
      Message.error(response?.msg || '更新失败')
      return false
    }

    Message.success('更新成功')
    emit('save-success')
    return true
  } catch (error: any) {
    console.error('保存失败:', error)
    Message.error(error.message || '保存失败')
    return false
  }
}

const onUpdate = async (record: DeviceCirculationUpdateReq) => {
  currentRecord.value = record.circulationId
  formState.value = {
    location: record.location || '',
    status: record.status !== undefined ? Number(record.status) : undefined,
    useTime: record.useTime || '',
    taskId: record.taskId ? Number(record.taskId) : undefined,
    userId: record.userId ? Number(record.userId) : undefined,
    backTime: record.backTime,
    scarpTime: record.scarpTime,
  }
  
  try {
    await Promise.all([
      fetchProjects(), // 加载项目列表
      handleUserSearch()
    ])
    
    // 如果已有任务ID，尝试加载对应的项目
    if (record.taskId) {
      // 这里需要根据任务ID查找对应的项目ID并设置
      // 可能需要添加额外的API调用或逻辑
    }
  } catch (error) {
    console.error('加载数据失败:', error)
  } finally {
    visible.value = true
  }
}

defineExpose({ onUpdate })
</script>

<style scoped lang="scss">
.table-page .ant-table th,
.table-page .ant-table td {
  padding: 8px;
}
.table-page .ant-table th {
  white-space: normal;
}

.project-task-card {
  margin-bottom: 16px;
  border-radius: 4px;
  background: var(--color-fill-2);
  border: 1px solid var(--color-border-2);
}

.project-task-card :deep(.arco-card-header) {
  border-bottom: 1px solid var(--color-border-2);
  padding: 12px 16px;
  font-weight: 500;
}
</style>